﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using NS_Controls;
using System.Collections;
using AjaxControlToolkit;
using System.Drawing;
using System.Web.UI.HtmlControls;

public partial class EditPacient : SessionControlBase
{
    public string pacientID
    {
        get { return (string)(this.ViewState["pacientID"] ?? ""); }
        set { this.ViewState["pacientID"] = value; }
    }
    public void Page_Load(object sender, EventArgs e)
    {
		//TabbedDetails.SetUrl(this, Request.RawUrl); //if (!~) SetMessage("Not found!", false);
		try
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    private void ShowMesaj(string mesaj)
    {
        ShowMesaj(mesaj, null);
    }
    private void ShowMesaj(string mesaj, string buttonText)
    {
        panelMesaj.Visible = true;
        literalMesaj.Text = mesaj;
        saveAnyway.Visible = buttonText != null;
        saveAnyway.Text = buttonText ?? "OK";
    }
    protected void CancelButtonMesaj_Click(object sender, EventArgs e)
    {
        panelMesaj.Visible = false;
    }

    private static readonly int nIdNeasigurat = 43;
    private void LoadData()
    {
        try
        {
            LoadGenericData();

			//if pacient was selected by id:
			pacientID = (this.Page.Request.QueryString["pacientID"] ?? "").Trim();
			TabbedDetails.ShowUrl(this, "action", pacientID.Length == 0 ? "new" : TabbedDetails.action[TabbedDetails.pacientTabIndex],
				"pacientID", pacientID);
			if ((pacientID.Length > 0) && !pacientID.Contains("'"))
				if (LoadDataPacientInfo(pacientID) == false)
					SetMessage("Pacientul selectat nu a fost gasit in baza de date.", true);
				else
				{
					tabelInformatiiExtinse.Visible = true; //show it even if an exception is thrown
					LoadDataInformatiiExtinse();
				}
		}
        catch (Exception ex)
        {
			Label target = null;
			if (ex.InnerException != null)
			{
				target = this.Page.Form.FindControl("lblMessages") as Label;
				if (target != null)
				{
					target.CssClass = "clsError";
					target.Text = ex.Message + " <!-- " + ex.InnerException.Message + System.Environment.NewLine + System.Environment.NewLine + (ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : "") + " -->";
					target.Visible = true;
					return;
				}
			}
			this.SetMessage(string.Format("[@'{0}'] {1}", this.ID, ex.Message), true);
		}
    }

    private void LoadGenericData()
    {
        DataSet ds;
        ds = Hipocrate.DB.DBConnection.GetData("select i.id , i.Name, i.drg_code, d.JudetNume from Insurers i left join drg_districts d on d.id = i.drg_code where active=1 order by i.ID");
        foreach (DataColumn c in ds.Tables[0].Columns) c.AllowDBNull = true;
		Tools.DataBindDDL(strInsurer, Tools.AddEmptyRow(ds), "ID", "Name");
        ds = Hipocrate.DB.DBConnection.GetData("select ID, JudetNume from DRG_DISTRICTS where Judet_Cod <> " + nIdNeasigurat.ToString());
        foreach (DataColumn c in ds.Tables[0].Columns) c.AllowDBNull = true;
		ds = Tools.AddEmptyRow(ds); //Tools.AddEmptyRow(ds, "ID", 0);
		Tools.DataBindDDL(strDistrictID, ds, "ID", "JudetNume");
		Tools.DataBindDDL(strBirthDistrictID, ds, "ID", "JudetNume");
		Tools.DataBindDDL(strResDistrictID, ds, "ID", "JudetNume");
		Tools.DataBindDDL(strCurrentResDistrictID, ds, "ID", "JudetNume");
        ds = Hipocrate.DB.DBConnection.GetData("select * from IDTypes order by Description");
        foreach (DataColumn c in ds.Tables[0].Columns) c.AllowDBNull = true;
		Tools.DataBindDDL(strIDType, Tools.AddEmptyRow(ds), "ID", "Description");
        ds = Hipocrate.DB.DBConnection.GetData("select * from Professions where active=1 order by Description");
        foreach (DataColumn c in ds.Tables[0].Columns) c.AllowDBNull = true;
		Tools.DataBindDDL(strProfession, Tools.AddEmptyRow(ds), "ID", "Description");
    }

	private bool LoadDataPacientInfo(string id)
	{
		DataSet ds = Hipocrate.DB.DBConnection.GetData("SELECT * FROM pacients WHERE id = " + id);
		if (ds.Tables[0].Rows.Count == 0) return false;
		DataRow info = ds.Tables[0].Rows[0];
		pacientID = info["id"].ToString();
		strFirstName.Text = info["FirstName"].ToString();
		strLastName.Text = info["LastName"].ToString();
		strInsurer.SelectedValue = info["InsurerID"].ToString();
		strInsuranceNo.Text = info["InsuranceNo"].ToString();
		strCNP.Text = info["CNP"].ToString();
		strIDType.SelectedValue = info["IDType"].ToString();
		strIDSeries.Text = info["IDSeries"].ToString();
		strIDNumber.Text = info["IDNumber"].ToString();
		strGender.SelectedValue = info["Sex"].ToString();
		if (info["BirthDate"] != DBNull.Value)
			strBirthDate.Text = ((DateTime)info["BirthDate"]).ToString(dateFormatString);
		strMother.Text = info["Mother"].ToString();
		strFather.Text = info["Father"].ToString();
		strZoneID.Text = info["ZoneID"].ToString();
		strBirthZoneID.Text = info["BirthZone"].ToString();
		UpdateMissingCityInfo();
		strWorkPlace.Text = info["WorkPlace"].ToString();
		strProfession.SelectedValue = info["ProfessionID"].ToString();
		strPhone.Text = info["Phone"].ToString();
		strGrSang.SelectedValue = info["GrSang"].ToString();
		strRH.SelectedValue = info["RH"].ToString();
		strAlergies.Text = info["Alergies"].ToString();
		strAttention.Text = info["Attention"].ToString();
		strOther.Text = info["Other"].ToString();
		strBornWeight.Text = info["BornWeight"].ToString();

        strResDistrictID.SelectedValue = info["ResDistrictID"].ToString();
        strResCityID.Text = info["ResCityID"].ToString();
        strResSector.SelectedValue = info["ResSector"].ToString();
        strStreetID.Text = info["StreetID"].ToString();
        strResStreetNo.Text = info["ResStreetNo"].ToString();
        strAddress.Text = info["Address"].ToString(); //name was saved into DB along with the id...

        strCurrentResDistrictID.SelectedValue = info["CurrentResDistrictID"].ToString();
        strCurrentResCityID.Text = info["CurrentResCityID"].ToString();
        strCurrentResSector.SelectedValue = info["CurrentResSector"].ToString();
        strCurrentResStreetID.Text = info["ResStreetID"].ToString();
        strCurrentResStreetNo.Text = info["CurrentResStreetNo"].ToString();
        strCurrentResStreet.Text = info["CurrentResStreet"].ToString(); //name was saved into DB along with the id...

        if (info["IsForeign"] != DBNull.Value)
            chkIsForeign.Checked = System.Convert.ToBoolean(info["IsForeign"]);
        if (info["isResident"] != DBNull.Value)
            chkIsResident.Checked = System.Convert.ToBoolean(info["isResident"]);
        return true;
    }
    private void LoadDataInformatiiExtinse()
    {
        DataSet ds = Hipocrate.DB.DBConnection.GetData(
            @"SELECT CONVERT(varchar(10),m.StartDate,103) as StartDate, 
				ISNULL(CONVERT(varchar(10),m.EndDate,103),'-') as EndDate,
				v.FullName
			FROM mf_subscriptions m
				INNER JOIN vMedics v ON v.id = m.MedicID
			WHERE m.PacientID = " + pacientID + /*@"
				AND v.SectionGroupID = '" + Session("MF_SGID") + "'" + */ @"
			ORDER BY m.StartDate DESC");
		resultsMedicFamilie.DataSource = ds;
		resultsMedicFamilie.ShowFooter = (ds.Tables[0].Rows.Count == 0);
		resultsMedicFamilie.DataBind();
		ds = Hipocrate.DB.DBConnection.GetData(@"SELECT DISTINCT DeclaredDate, ID, CheckInID, sDeclaredDate, sDeclaredTime, sDeclaredDate + ' ' + sDeclaredTime as sDeclaredDateTime, SectionName, MedicFullName, SenderObs, PresReason
			FROM vPresentationFull WHERE PacientID=" + pacientID + @"
			AND EXISTS (SELECT * FROM sections s WHERE s.code=vPresentationFull.SectionID AND s.UniPresentation=1)
			ORDER BY DeclaredDate DESC");
        resultsDosareMedicale.DataSource = ds;
        resultsDosareMedicale.ShowFooter = (ds.Tables[0].Rows.Count == 0);
        resultsDosareMedicale.DataBind();
        ds = Hipocrate.DB.DBConnection.GetData(@"SELECT DISTINCT ID as PresentationID, CheckInID, sDeclaredDate as sDate, sDeclaredTime as sTime,
				SectionName, MedicFullName, SenderObs, PresReason as Reason, DeclaredDate as Chronology
			FROM vPresentationFull
			WHERE PacientID=" + pacientID + @"
			ORDER BY DeclaredDate DESC"/*
			UNION
			SELECT CONVERT(varchar(10),PresDate,103) as sDate, convert(varchar(5),PresDate,108) as sTime,
				convert(varchar(10),CIDate,103) as sCIDate, convert(varchar(5),CIDate,108) as sCITime,
				convert(varchar(10),CODate,103) as sCODate,  convert(varchar(5),CODate,108) as sCOTime,
				e.*, p.CUID as NastereID, PresDate as Chronology
			 from EPISODES e inner join pacients p on p.id = e.pacientid where PacientID=" + pacientID + @"
			 order by PresDate desc"*/ );
		resultsEvenimente.DataSource = ds;
		resultsEvenimente.DataBind();
	}

	private void UpdateMissingCityInfo()
	{
		List<string> ids = new List<string>();
		string zoneID = strZoneID.Text.Trim();
		if (zoneID.Length > 0)
			ids.Add(zoneID);
		string birthZoneID = strBirthZoneID.Text.Trim();
		if (birthZoneID.Length > 0)
			ids.Add(birthZoneID);
		if (ids.Count == 0)
			return; //nothing to do
		string condition = " WHERE Localitate_Cod = " + ids[0];
		if (ids.Count > 0)
			condition = string.Format(" WHERE Localitate_Cod IN ({0})", string.Join(", ", ids.ToArray()));
		DataSet ds = Hipocrate.DB.DBConnection.GetData("SELECT Localitate_Cod, LocalitateNume, LocalitateNume_Old, LocalitateJudet_ID FROM drg_city " + condition);
		DataTable dt = ds.Tables[0];
		dt.Constraints.Add("pkInfo", dt.Columns["Localitate_Cod"], true);
		DataRowCollection info = dt.Rows;
		if (zoneID.Length > 0)
		{
			DataRow dr = info.Find(zoneID);
			strDistrictID.Text = dr["LocalitateJudet_ID"].ToString();
			strZoneName.Text = dr["LocalitateNume_Old"].ToString(); //NB: LocalitateNume is all caps
		}
		if (birthZoneID.Length > 0)
		{
			DataRow dr = info.Find(birthZoneID);
			strBirthDistrictID.Text = dr["LocalitateJudet_ID"].ToString();
			strBirthZoneName.Text = dr["LocalitateNume_Old"].ToString(); //NB: LocalitateNume is all caps
		}
	}

	private bool overrideCnpValidity = false;
    protected void saveAnyway_Click(object sender, EventArgs e)
    {
        overrideCnpValidity = true;
        btnSave_Click(sender, e);
        CancelButtonMesaj_Click(null, null);
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if ((!overrideCnpValidity) && (IsValidCNP() != true)) //NB: either false OR NULL (!)
        {
            ShowMesaj(@"Campul CNP este obligatoriu pentru decontarile catre CAS. <br/><br/>
				Sunteti sigur ca doriti inregistrarea informatiilor fara a completa acest camp?", "Da, Salveaza...");
            return;
        }
        try
        {
            string[] paramNames = new string[] { "@strPacID", "@strFirstName", "@strLastName",
				//"@strNewBorn", "@strMotherID", "@strCUID",
				"@strCNP", "@strInsurer", "@strinsuranceNo",
				"@strIDType", "@strIDSeries", "@strIDNumber",
				"@strSex", "@strBirthDate", "@strMother", "@strFather",
				"@strZone", "@DistrictID",
				"@strBirthZone", "@strWorkPlace", "@intProfessionID", //"@profType",
				"@strPhone", "@strGrSang", "@strRH",
				"@strAlergies", "@strAttention", "@strOther", "@strMedicID", "@BornWeight",
				"@ResDistrictID", "@ResCityID", "@ResSector", "@StreetID", "@strAddress", "@ResStreetNo",
				"@CurrentResDistrictID", "@CurrentResCityID", "@CurrentResSector", "@ResStreetID", "@CurrentResStreet", "@CurrentResStreetNo",
				//"@CitizenshipID", "@CitizenshipTypeID", "@strEmail", "@InsuranceTypeID", "@EmploymentStructureID",
				"@curentApart", "@resApart", "@curentScara", "@resScara", "@strbloc", "@strEtaj", "@strPost",
				"@isForeign", "@IsResident", "@IsCNPValid" };//*/
			object[] paramValues = new object[] { pacientID, strFirstName.Text.Trim(), strLastName.Text.Trim(),
				//false, null, null,
				strCNP.Text.Trim(), GetValue(strInsurer), NullIfEmpty(strInsuranceNo.Text),
				GetValue(strIDType), NullIfEmpty(strIDSeries.Text), NullIfEmpty(strIDNumber.Text),
				GetValue(strGender), GetBirthDate(), NullIfEmpty(strMother.Text), NullIfEmpty(strFather.Text),
				NullIfEmpty(strZoneID.Text), strDistrictID.Text, //NB: DistrictID is not used!
				NullIfEmpty(strBirthZoneID.Text), NullIfEmpty(strWorkPlace.Text), GetValue(strProfession), //0,
				NullIfEmpty(strPhone.Text), GetValue(strGrSang), GetValue(strRH), //.Equals("1")
				NullIfEmpty(strAlergies.Text), NullIfEmpty(strAttention.Text), NullIfEmpty(strOther.Text), null, NullIfEmpty(strBornWeight.Text), //TODO: current Medic ID!
				GetValue(strResDistrictID), NullIfEmpty(strResCityID.Text), GetValue(strResSector), NullIfEmpty(strStreetID.Text), NullIfEmpty(strAddress.Text), NullIfEmpty(strResStreetNo.Text),
				GetValue(strCurrentResDistrictID), NullIfEmpty(strCurrentResCityID.Text), GetValue(strCurrentResSector), NullIfEmpty(strCurrentResStreetID.Text), NullIfEmpty(strCurrentResStreet.Text), NullIfEmpty(strCurrentResStreetNo.Text),
				//null, null, null, null, null, //currently not implemented...
				null, null, null, null, null, null, null,
				chkIsForeign.Checked, chkIsResident.Checked, IsValidCNP() };

            int result = Hipocrate.DB.DBConnection.Execute("Pacient_Save", paramNames, paramValues);
            this.SetMessage("Informatiile au fost salvate. <!-- R = " + result.ToString() + " -->", false);
            //TODO: show pacient data?
            //Response.Redirect("~/Default.aspx?action=search"); // "files/presentation.asp?pacid=" + strPacID;
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    protected void strBirthDate_TextChanged(object sender, EventArgs e)
    {
        DateTime? result = GetBirthDate();
        if (result != null)
            strBirthDate.Text = ((DateTime)result).ToString(dateFormatString);
        //***KNOWN ISSUES***
        //in extreme cases, when the year is outside the 1000-9999 range, the Calendar goes awry and also prevents the textbox from being changed...
        //Also, "un-representable" dates prevent this server code from being run in the first place. :-|
        //	Un-representable means no such date (february 31st) or year > 9999.
    }
    private DateTime? GetBirthDate()
    {
        try
        {
            strBirthDate.BackColor = System.Drawing.Color.White;
            return GetDate(strBirthDate.Text);
        }
        catch (ApplicationException ex)
        {
            strBirthDate.BackColor = System.Drawing.Color.Pink;
            SetMessage(ex.Message, true);
            return null;
        }
        catch (FormatException)
        {
            strBirthDate.BackColor = System.Drawing.Color.Pink;
            SetMessage("Valoarea introdusa nu reprezinta o data valida!", true);
            return null;
        }
        catch (Exception ex)
        {
            strBirthDate.BackColor = System.Drawing.Color.Pink;
            SetMessage("! " + ex.GetType().ToString() + " : " + ex.Message, true);
            throw;
        }
    }
    private static readonly string dateFormatString = "dd.MM.yyyy";
    private DateTime? GetDate(string input)
    {
        input = input.Trim();
        if (input.Length == 0) return null;
        DateTime value;
        if (DateTime.TryParse(input, out value))
        {
            string parsed = value.ToString(dateFormatString);
            if (parsed.Equals(input))
                return value;
            parsed = parsed.Substring(0, 2) + ' ' + parsed.Substring(3, 2) + ' ' + parsed.Substring(6);
            if (parsed.Equals(input.Substring(0, 2) + ' ' + input.Substring(3, 2) + ' ' + input.Substring(6)))
                return value;
        }
        //throw new ApplicationException("Date was not in the required format! Value = " + input);
        //parse it properly:
        if (input.Length < 5)
            throw new FormatException(); // not enough space for all parts
        int separator1 = char.IsDigit(input[1]) ? 2 : 1;
        int separator2 = char.IsDigit(input[separator1 + 2]) ? separator1 + 3 : separator1 + 2;
        if (input.Length < (separator2 + 2))
            throw new FormatException(); // not enough space for the year
        int day = int.Parse(input.Substring(0, separator1));
        int month = int.Parse(input.Substring(separator1 + 1, separator2 - separator1 - 1));
        int year = int.Parse(input.Substring(separator2 + 1));
        if (year < 100)
        {
            int century = (DateTime.Now.Year / 100);
            year += century * 100;
            if (year > DateTime.Now.Year)
                year -= 100;
        }
        return new DateTime(year, month, day);
    }

    private object GetValue(DropDownList target)
    {
        return NullIfEmpty(target.SelectedValue);
    }
    private object NullIfEmpty(string input)
    {
        return input.Trim().Length == 0 ? null : input;
    }

    protected void btnsearch_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx?action=search");
    }

	protected void strInsurer_SelectedIndexChanged(object sender, EventArgs e)
	{
		string selectedText = strInsurer.SelectedItem.Text;
		if (selectedText.StartsWith("CJAS"))
		{
			//allow restoring of previous values:
			ViewState["CitySearchedFor"] = txtCityName.Text + ";" + strCityType.SelectedValue;
			selectedText = selectedText.Replace("CJAS ", "");
			foreach (ListItem county in strDistrictID.Items)
				if (county.Text.Equals(selectedText))
				{
					strDistrictID.SelectedValue = county.Value;
					break;
				}
			literalHiddenJudetId.Text = strDistrictID.SelectedValue;
			strCityType.SelectedValue = "u";
			if (selectedText.Equals("BUCURESTI"))
			{
				txtCityName.Text = selectedText;
				imgLinkZoneName_Click(null, null);
			}
			else
			{
				txtCityName.Text = CountySeatMapping[selectedText].ToString();
				btnCautaLocalitate_Click(null, null);
				int code = int.MaxValue;
				//DEBUG: strOther.Text = ShowControlTree(repeaterResultsLocalitate.Items[0], 0);
				foreach (RepeaterItem city in repeaterResultsLocalitate.Items)
				{//NB: no DataItem available;
					int current = int.Parse((city.FindControl("cod").Controls[0] as DataBoundLiteralControl).Text);
					if (current < code)
					{
						code = current;
						selectedText = (city.FindControl("nume").Controls[0] as DataBoundLiteralControl).Text;
					}
				}
				strZoneID.Text = code.ToString();
				strZoneName.Text = selectedText;
			}
		}
		else
			strDistrictID.SelectedIndex = 0;
	}

	static Hashtable countySeatMapping = null;
	private Hashtable CountySeatMapping
	{
		get
		{
			if (countySeatMapping == null)
			{
				countySeatMapping = new Hashtable();
				countySeatMapping["ALBA"] = "Alba Iulia";
				countySeatMapping["ARAD"] = "Arad";
				countySeatMapping["ARGES"] = "Pitesti";
				countySeatMapping["BACAU"] = "Bacau";
				countySeatMapping["BIHOR"] = "Oradea";
				countySeatMapping["BISTRITA-NASAUD"] = "Bistrita";
				countySeatMapping["BOTOSANI"] = "Botosani";
				countySeatMapping["BRAILA"] = "Braila";
				countySeatMapping["BRASOV"] = "Brasov";
				countySeatMapping["BUZAU"] = "Buzau";
				countySeatMapping["CALARASI"] = "Calarasi";
				countySeatMapping["CARAS-SEVERIN"] = "Resita";
				countySeatMapping["CLUJ"] = "CLUJ-NAPOCA";
				countySeatMapping["CONSTANTA"] = "Constanta";
				countySeatMapping["COVASNA"] = "SFANTUL GHEORGHE";
				countySeatMapping["DIMBOVITA"] = "Targoviste";
				countySeatMapping["DOLJ"] = "Craiova";
				countySeatMapping["GALATI"] = "Galati";
				countySeatMapping["GIURGIU"] = "Giurgiu";
				countySeatMapping["GORJ"] = "Targu Jiu";
				countySeatMapping["HARGHITA"] = "MIERCUREA CIUC";
				countySeatMapping["HUNEDOARA"] = "Deva";
				countySeatMapping["IALOMITA"] = "Slobozia";
				countySeatMapping["IASI"] = "Iasi";
				countySeatMapping["ILFOV"] = "Buftea";
				countySeatMapping["MARAMURES"] = "Baia Mare";
				countySeatMapping["MEHEDINTI"] = "Drobeta-Turnu Severin";
				countySeatMapping["MURES"] = "Targu Mures";
				countySeatMapping["NEAMT"] = "Piatra Neamt";
				countySeatMapping["OLT"] = "Slatina";
				countySeatMapping["PRAHOVA"] = "Ploiesti";
				countySeatMapping["SALAJ"] = "Zalau";
				countySeatMapping["SATU MARE"] = "Satu Mare";
				countySeatMapping["SIBIU"] = "Sibiu";
				countySeatMapping["SUCEAVA"] = "Suceava";
				countySeatMapping["TELEORMAN"] = "Alexandria";
				countySeatMapping["TIMIS"] = "Timisoara";
				countySeatMapping["TULCEA"] = "Tulcea";
				countySeatMapping["VASLUI"] = "Vaslui";
				countySeatMapping["VILCEA"] = "Ramnicu Valcea";
				countySeatMapping["VRANCEA"] = "Focsani";
			}
			return countySeatMapping;
		}
	}
	private string ShowControlTree(Control startAt, int level)
	{
		string prefix = new string('*', 3 * level);
		string result = prefix + startAt.ID + " : " + startAt.GetType().ToString() + System.Environment.NewLine;
		if (startAt.Controls.Count > 0)
		{
			result += prefix + "vvv" + System.Environment.NewLine;
			foreach (Control c in startAt.Controls)
				result += ShowControlTree(c, level + 1);
			result += prefix + "^^^" + System.Environment.NewLine;
		}
		return result;
	}

    protected void strCNP_TextChanged(object sender, EventArgs e)
    {
        if (chkIsForeign.Checked) return; //cannot check ID codes
        strCNP.BackColor = Color.White;
        strCNP.Text = strCNP.Text.Trim();
        if (strCNP.Text.Length == 0) return;
        decimal d;
        if (Decimal.TryParse(strCNP.Text, out d))
        {
            if (validateCNP(strCNP.Text))
            {
                if (strBirthDate.Text.Trim().Length == 0)
                {
                    DateTime result = getBirthDateFromCNP(strCNP.Text);
                    if (result < DateTime.Now.AddDays(1))
                        strBirthDate.Text = result.ToString(dateFormatString);
                }
                if (strGender.SelectedIndex == 0)
                {
                    string sGender = getGenderFromCNP(strCNP.Text);
                    //if (sGender.Equals("I")) {alert("Campul CNP este invalid!");} else
                    strGender.SelectedIndex = (sGender == "F" ? 1 : (sGender == "M" ? 2 : 0));
                }
                return;
            }
        }
        strCNP.BackColor = Color.Pink;
    }
    private bool? IsValidCNP()
    {
        if (chkIsForeign.Checked) return null;
        if (strCNP.Text.Length == 0) return null;
        decimal d;
        if (!Decimal.TryParse(strCNP.Text, out d))
            return false;
        return validateCNP(strCNP.Text);
    }
    private bool validateCNP(string strCNP)
    {
        if (strCNP.Length != 13) return false;
        char[] digits = strCNP.ToCharArray();
        foreach (char c in digits) if (!char.IsDigit(c)) return false;

        int S1, A2, A3, L4, L5, Z6, Z7, J8, J9, N10, N11, N12, C13;
        S1 = digits[0] - '0';
        A2 = digits[1] - '0';
        A3 = digits[2] - '0';
        L4 = digits[3] - '0';
        L5 = digits[4] - '0';
        Z6 = digits[5] - '0';
        Z7 = digits[6] - '0';
        J8 = digits[7] - '0';
        J9 = digits[8] - '0';
        N10 = digits[9] - '0';
        N11 = digits[10] - '0';
        N12 = digits[11] - '0';
        C13 = digits[12] - '0';
        int sum = (S1 * 2) + (A2 * 7) + (A3 * 9) + (L4 * 1) + (L5 * 4) + (Z6 * 6) + (Z7 * 3) + (J8 * 5) + (J9 * 8) + (N10 * 2) + (N11 * 7) + (N12 * 9);
        int C = sum % 11;

        C = C / 10 + C % 10; //if (C == 10) C = 1;
        return (C == C13);
    }
    private string getGenderFromCNP(string strCNP)
    {
        char gender = strCNP[0];
        switch (gender)
        {
            case '1': // 19**
            case '3': // 18**
            case '5': // 20**
            case '7': // rezidenti
                return "M";
            case '2': // 19**
            case '4': // 18**
            case '6': // 20**
            case '8': // rezidente
                return "F";
            case '9':
                return ""; //cetateni straini... unspecified gender
            default:
                return "I"; //invalid
        }
    }
    private DateTime getBirthDateFromCNP(string strCNP)
    {
        int century = 1900;
        switch (strCNP[0])
        {
            case '1':
            case '2':
                century = 1900;
                break;
            case '3':
            case '4':
                century = 1800;
                break;
            case '5':
            case '6':
                century = 2000;
                break;
            default:
                return DateTime.MaxValue;
        }
        int an = century + (strCNP[1] - '0') * 10 + (strCNP[2] - '0');
        int luna = (strCNP[3] - '0') * 10 + (strCNP[4] - '0');
        int zi = (strCNP[5] - '0') * 10 + (strCNP[6] - '0');
        return new DateTime(an, luna, zi);
    }

	private string backupCNP
	{
		get { return (this.ViewState["backupCNP"] ?? "").ToString(); }
		set { this.ViewState["backupCNP"] = value; }
	}
	protected void chkIsForeign_CheckedChanged(object sender, EventArgs e)
	{
		lblIsResident.Visible = chkIsForeign.Checked;
		chkIsResident.Visible = chkIsForeign.Checked;
		strCNPLabel.Text = (chkIsForeign.Checked ? "Cod identificare" : "CNP");
		chkIsResident_CheckedChanged(sender, null);
		if (strCNP.Enabled)
		{
			strCNP.Text = backupCNP;
			strCNP_TextChanged(null, null);
		}
		else
		{
			backupCNP = strCNP.Text;
			strCNP.Text = "";
			strCNP.BackColor = Color.White;
		}
	}
	protected void chkIsResident_CheckedChanged(object sender, EventArgs e)
	{
		strCNP.Enabled = chkIsResident.Checked || !chkIsForeign.Checked;
	}

	protected void strDistrictID_SelectedIndexChanged(object sender, EventArgs e)
	{
		strZoneID.Text = "";
		strZoneName.Text = "";
		if (strDistrictID.SelectedIndex > 0)
		{
			imgLinkZoneName_Click(null, null);
			modalLocalitate.Show();
		}
	}
    protected void imgLinkZoneName_Click(object sender, EventArgs e)
    {
        if (!JudetSelectat(strDistrictID)) return;
        ViewState["TargetControlIDLocalitate"] = "strZoneID";
        ViewState["TargetControlLocalitate"] = "strZoneName";
        SetContextLocalitate(strDistrictID.SelectedValue, strDistrictID.SelectedItem.Text);
        panelLocalitate.Visible = true;
        //SetValidators(false);
    }

	protected void strBirthDistrictID_SelectedIndexChanged(object sender, EventArgs e)
	{
		strBirthZoneID.Text = "";
		strBirthZoneName.Text = "";
		if (strBirthDistrictID.SelectedIndex > 0)
		{
			imgLinkBirthZoneName_Click(null, null);
			modalLocalitate.Show();
		}
	}
    protected void imgLinkBirthZoneName_Click(object sender, EventArgs e)
    {
        if (!JudetSelectat(strBirthDistrictID)) return;
        ViewState["TargetControlIDLocalitate"] = "strBirthZoneID";
        ViewState["TargetControlLocalitate"] = "strBirthZoneName";
        SetContextLocalitate(strBirthDistrictID.SelectedValue, strBirthDistrictID.SelectedItem.Text);
        panelLocalitate.Visible = true;
        //SetValidators(false);
    }
	protected void strResDistrictID_SelectedIndexChanged(object sender, EventArgs e)
	{
		strResCityID.Text = "";
		strResCityName.Text = "";
		if (strResDistrictID.SelectedIndex > 0)
		{
			imgLinkResCityName_Click(null, null);
			modalLocalitate.Show();
		}
	}
    protected void imgLinkResCityName_Click(object sender, EventArgs e)
    {
        if (!JudetSelectat(strResDistrictID)) return;
        ViewState["TargetControlIDLocalitate"] = "strResCityID";
        ViewState["TargetControlLocalitate"] = "strResCityName"; //NB: there's also "strResCityHiddenName"...
        SetContextLocalitate(strResDistrictID.SelectedValue, strResDistrictID.SelectedItem.Text);
        panelLocalitate.Visible = true;
        //SetValidators(false);
    }
	protected void strCurrentResDistrictID_SelectedIndexChanged(object sender, EventArgs e)
	{
		strCurrentResCityID.Text = "";
		strCurrentResCityName.Text = "";
		if (strCurrentResDistrictID.SelectedIndex > 0)
		{
			imgLinkCurrentResCityName_Click(null, null);
			modalLocalitate.Show();
		}
	}
    protected void imgLinkCurrentResCityName_Click(object sender, EventArgs e)
    {
        if (!JudetSelectat(strCurrentResDistrictID)) return;
        ViewState["TargetControlIDLocalitate"] = "strCurrentResCityID";
        ViewState["TargetControlLocalitate"] = "strCurrentResCityName";
        SetContextLocalitate(strCurrentResDistrictID.SelectedValue, strCurrentResDistrictID.SelectedItem.Text);
        panelLocalitate.Visible = true;
        //SetValidators(false);
    }
    private void SetContextLocalitate(string judetID, string judetName)
    {
        literalHiddenJudetId.Text = judetID;
        literalNumeJudet.Text = judetName;
		//erase old values:
		strCityType.SelectedIndex = 0;
		txtCityName.Text = "";
		if (ViewState["CitySearchedFor"] != null)
		{
			string[] info = ViewState["CitySearchedFor"].ToString().Split(';');
			txtCityName.Text = info[0];
			strCityType.SelectedValue = (info[1].Equals("u") ? "(urban)" : info[1].Equals("r") ? "(rural)" : info[1]);
			if (info.Length > 2)
				strDRGCode.Text = info[2];
		}
		btnCautaLocalitate_Click(null, null);
    }
    private bool JudetSelectat(DropDownList target)
    {
        if (target.SelectedIndex == 0)
        {
            ShowMesaj("Alegeti intai judetul...");
            target.BackColor = System.Drawing.Color.Yellow;
            return false;
        }
        //panelMesaj.Visible = false;
        target.BackColor = System.Drawing.Color.White;
        return true;
    }
    protected void CancelButtonLocalitate_Click(object sender, EventArgs e)
    {
        ViewState["TargetControlIDLocalitate"] = null;
        ViewState["TargetControlLocalitate"] = null;
        panelLocalitate.Visible = false;
    }
    protected void btnCautaLocalitate_Click(object sender, EventArgs e)
    {
		if (sender != null)
			modalLocalitate.Show();
        string zoneID = literalHiddenJudetId.Text;
        //string zoneName = literalNumeJudet.Text;
        string sql = "SELECT * FROM drg_city WHERE LocalitateJudet_ID = " + zoneID;
        string cityName = txtCityName.Text.Trim();
        if (cityName.Length > 0)
            sql += "AND LocalitateNume LIKE '%" + cityName.Replace("'", "''") + "%' ";
        if (strCityType.SelectedIndex > 0)
            sql += "AND LocalitateUrbanRural = '" + strCityType.SelectedValue + "'";
        string drgCode = strDRGCode.Text.Trim();
        if (drgCode.Length > 0)
            sql += "AND Localitate_cod LIKE '%" + drgCode.Replace("'", "''") + "%' ";
        sql += " ORDER BY LocalitateNume";
        DataSet ds = Hipocrate.DB.DBConnection.GetData(sql);
        repeaterResultsLocalitate.DataSource = ds;
        repeaterResultsLocalitate.DataBind();
        bool eraseOldData = true;
        if (selectedDrgCode.Text.Length > 0)
        {
            DataTable dt = ds.Tables[0];
            dt.Constraints.Add("pkCity", dt.Columns["Localitate_cod"], true);
            eraseOldData = (dt.Rows.Find(selectedDrgCode.Text) == null);
        }
        if (eraseOldData)
        {
            selectedCity.Text = "";
            statusUrbanRural.Text = "";
            selectedDrgCode.Text = "";
        }
    }
    protected void repeaterResultsLocalitate_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Footer) || (e.Item.ItemType == ListItemType.Header))
            return;
        //string all = "";
        DataRowView row = e.Item.DataItem as DataRowView;
        string cmdArg = (row["LocalitateNume"]).ToString() + ";" + (row["LocalitateUrbanRural"]).ToString() + ";" + (row["Localitate_Cod"]).ToString();
        foreach (Control c in e.Item.Controls)
        {
            //all += c.GetType().ToString();
            if (c is LinkButton)
                (c as LinkButton).CommandArgument = cmdArg;
        }
        //labelLocalitate.Text = all;
    }
    protected void SelectLocalitate(object sender, EventArgs e)
    {
		modalLocalitate.Show();
        if (sender is LinkButton)
        {
            string[] info = (sender as LinkButton).CommandArgument.Split(';');
            selectedCity.Text = info[0];
            statusUrbanRural.Text = (info[1].Equals("u") ? "(urban)" : info[1].Equals("r") ? "(rural)" : info[1]);
            selectedDrgCode.Text = info[2];
			if (true) //TODO: config setting
				btnSaveLocalitate_Click(null, null);
        }
        else
            ShowMesaj("DEBUG info: this shouldn't really happen... <!-- sender @ SelectLocalitate is NOT linkButton!!! -->");
    }
    protected void btnSaveLocalitate_Click(object sender, EventArgs e)
    {
		SetValidators(true);
        string sID = selectedDrgCode.Text;
        //ViewState["CountSaveLocalitate"] = 1 + (int)(ViewState["CountSaveLocalitate"] ?? 0);
        string sNume = selectedCity.Text; // "it worked " + ViewState["CountSaveLocalitate"].ToString();
        ((Literal)upPacient.FindControl(ViewState["TargetControlIDLocalitate"].ToString())).Text = sID;
        string targetControlLocalitate = ViewState["TargetControlLocalitate"].ToString();
        ((TextBox)upPacient.FindControl(targetControlLocalitate)).Text = sNume;
        string targetControlSector = targetControlLocalitate.Replace("CityName", "Sector");
		Control targetSector = upPacient.FindControl(targetControlSector);
		if (sNume.ToLower().Contains("sector") && (!targetControlSector.Equals(targetControlLocalitate)) && (targetSector != null))
        {
            int index = sNume.IndexOf(' ', sNume.IndexOf("sector", StringComparison.InvariantCultureIgnoreCase));
            string sector = sNume.Substring(index).Trim();
            if (sector.Contains(' ')) sector = sector.Substring(0, sector.IndexOf(' '));
			//debug:
			//((TextBox)upPacient.FindControl(targetControlSector.Replace("Sector", "StreetNo"))).Text = sector;
			(targetSector as DropDownList).SelectedValue = sector;
        }
		else
			(targetSector as DropDownList).SelectedValue = "";
        panelLocalitate.Visible = false;
	}

	protected void imgLinkStreetAddress_Click(object sender, EventArgs e)
	{
		if (!LocalitateSelectata(strResCityName)) return;
		ViewState["TargetControlIDStrada"] = "strStreetID";
		ViewState["TargetControlStrada"] = "strAddress";
		SetContextStrada(strResCityID.Text, strResCityName.Text, strAddress.Text);
		panelStrada.Visible = true;
		//SetValidators(false);
	}
	protected void imgLinkCurrentResStreetAddress_Click(object sender, EventArgs e)
	{
		if (!LocalitateSelectata(strCurrentResCityName)) return;
		ViewState["TargetControlIDStrada"] = "strCurrentResStreetID";
		ViewState["TargetControlStrada"] = "strCurrentResStreet";
		SetContextStrada(strCurrentResCityID.Text, strCurrentResCityName.Text, strCurrentResStreet.Text);
		panelStrada.Visible = true;
		//SetValidators(false);
	}
	private void SetContextStrada(string cityID, string cityName, string streetName)
	{
		literalHiddenCityId.Text = cityID;
		literalNumeLocalitate.Text = cityName;
		txtStreetName.Text = streetName;
		btnCautaStrada_Click(null, null);
	}
	private bool LocalitateSelectata(TextBox target)
	{
		if (target.Text.Length == 0)
		{
			ShowMesaj("Alegeti intai localitatea...");
			target.BackColor = System.Drawing.Color.Yellow;
			return false;
		}
		//panelMesaj.Visible = false;
		target.BackColor = System.Drawing.Color.White;
		return true;
	}
	protected void CancelButtonStrada_Click(object sender, EventArgs e)
	{
		ViewState["TargetControlIDStrada"] = null;
		ViewState["TargetControlStrada"] = null;
		panelStrada.Visible = false;
	}
	protected void btnCautaStrada_Click(object sender, EventArgs e)
	{
		string cityID = literalHiddenCityId.Text;
		string sql = @"SELECT s.code, s.name, s.id FROM streets s
						INNER JOIN drg_city dc ON dc.siui_code = s.citycode
						WHERE dc.id = " + cityID + " AND name IS NOT NULL ";

        string streetName = txtStreetName.Text.Trim();
        if (streetName.Length > 0)
            sql += "AND name LIKE '%" + streetName.Replace("'", "''") + "%' ";
        sql += " ORDER BY Name";
        DataSet ds = null;
		try
		{
			ds = Hipocrate.DB.DBConnection.GetData(sql);
		}
		catch (ApplicationException ex)
		{
			if (ex.InnerException != null)
				SetMessage(ex.InnerException.InnerException.Message, true);
			else
				SetMessage(sql, true);
			panelStrada.Style.Remove("top");
			panelStrada.Style.Add("top", "200px");
			return;
		}
        repeaterResultsStrada.DataSource = ds;
        repeaterResultsStrada.DataBind();
        bool eraseOldData = true;
        if (selectedStreetID.Text.Length > 0)
        {
            DataTable dt = ds.Tables[0];
            dt.Constraints.Add("pkStreet", dt.Columns["code"], true);
            eraseOldData = (dt.Rows.Find(selectedStreetID.Text) == null);
        }
        if (eraseOldData)
        {
            selectedStreet.Text = "";
            selectedStreetID.Text = "";
        }
    }
    protected void repeaterResultsStrada_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Footer) || (e.Item.ItemType == ListItemType.Header))
            return;
        DataRowView row = e.Item.DataItem as DataRowView;
        string cmdArg = (row["Code"]).ToString() + ";" + (row["Name"]).ToString();
        foreach (Control c in e.Item.Controls)
        {
            if (c is LinkButton)
                (c as LinkButton).CommandArgument = cmdArg;
        }
    }
    protected void SelectStrada(object sender, EventArgs e)
    {
        if (sender is LinkButton)
        {
            string[] info = (sender as LinkButton).CommandArgument.Split(';');
            selectedStreetID.Text = info[0];
            selectedStreet.Text = info[1];
			if (true) //TODO: config setting
				btnSaveStrada_Click(null, null);
		}
        else
            ShowMesaj("DEBUG info: this shouldn't really happen... <!-- sender @ SelectStrada is NOT linkButton!!! -->");
    }
    protected void btnSaveStrada_Click(object sender, EventArgs e)
    {
        SetValidators(true);
        string sID = selectedStreetID.Text;
        //ViewState["CountSaveStrada"] = 1 + (int)(ViewState["CountSaveStrada"] ?? 0);
        string sNume = selectedStreet.Text; // "it worked " + ViewState["CountSaveStrada"].ToString();
        ((Literal)upPacient.FindControl(ViewState["TargetControlIDStrada"].ToString())).Text = sID;
        ((TextBox)upPacient.FindControl(ViewState["TargetControlStrada"].ToString())).Text = sNume;
        panelStrada.Visible = false;
    }

    protected void resultsMedicFamilie_ItemCreated(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            ImageButton b = new ImageButton();
            b.BorderWidth = 0;
            b.ImageUrl = "~/Images/add.png";
            b.ToolTip = "Click pentru a adauga";
            b.Width = b.Height = 20;
            e.Item.Cells[resultsMedicFamilie.Columns.Count - 1].Controls.Add(b);
            e.Item.Cells[resultsMedicFamilie.Columns.Count - 1].HorizontalAlign = HorizontalAlign.Center;
        }
        if (e.Item.ItemType == ListItemType.Footer)
        {
            e.Item.Cells[0].ColumnSpan = resultsMedicFamilie.Columns.Count;
            e.Item.Cells[0].Text = "<br/>&nbsp;&nbsp;Nu au fost gasite informatii despre medicul de familie al pacientului.<br/>&nbsp;";
            while (e.Item.Cells.Count > 1)
                e.Item.Cells.RemoveAt(1);
        }
    }

	protected void resultsDosareMedicale_ItemCreated(object sender, DataGridItemEventArgs e)
	{
		if (e.Item.ItemType == ListItemType.Footer)
		{
			e.Item.Cells[0].ColumnSpan = resultsDosareMedicale.Columns.Count;
			e.Item.Cells[0].Text = "<br/>&nbsp;&nbsp;Nu au fost gasite dosare medicale ale pacientului.<br/>&nbsp;";
			while (e.Item.Cells.Count > 1)
				e.Item.Cells.RemoveAt(1);
		}
	}
	protected void resultsDosareMedicale_ItemDataBound(object sender, DataGridItemEventArgs e)
	{
		if (e.Item.DataItem != null)
			if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
				((LinkButton)e.Item.Cells[0].Controls[0]).CommandArgument = (e.Item.DataItem as DataRowView)["id"].ToString();
	}
	protected void resultsDosareMedicale_ItemCommand(object source, DataGridCommandEventArgs e)
	{
		//TODO: redirect to: string.Format("~/files/presentation.asp?pacid={0}&id={1}", pacientID, e.CommandArgument);
		SetMessage(e.CommandArgument.ToString(), false);
	}

    protected void resultsEvenimente_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            DataRowView data = e.Item.DataItem as DataRowView;
            object checkInID = data["CheckInID"];
            bool hasCheckIn = ((checkInID != DBNull.Value) && (checkInID != null));
            Repeater detaliiEvolutie = e.Item.FindControl("detaliiEvolutie") as Repeater;
            detaliiEvolutie.Visible = hasCheckIn;
            if (hasCheckIn)
            {
                detaliiEvolutie.DataSource = Hipocrate.DB.DBConnection.GetData(
                    @"(SELECT DISTINCT 'Externare' as eType, COID as ID, '' as RefID, sCODate as sDate, sCOTime as sTime, SectionName, MedicFullName, CODiagnosis as Diagnosis, CODiagnosisName as DiagnosisName, 0 as Cancel, CODate as Chronology, 0 as TransferID
					FROM vCheckOutFull WHERE CIID = " + checkInID + @")
					UNION
					(SELECT DISTINCT 'Internare' as eType, CIID as ID,   RefID, sCIDate as sDate, sCITime as sTime, SectionName, MedicFullName, CIDiagnosis as Diagnosis, CIDiagnosisName as DiagnosisName,   Cancel, CIDate as Chronology, TransferID
					FROM vCheckInFull WHERE CIID = " + checkInID + @")
					ORDER BY Chronology DESC, TransferID DESC");
				detaliiEvolutie.DataBind();
			}
			(e.Item.FindControl("linkPresentation") as LinkButton).CommandArgument = data["PresentationID"].ToString();
		}
	}
	protected void detaliiEvolutie_ItemDataBound(object sender, RepeaterItemEventArgs e)
	{
		if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
		{
			DataRowView data = e.Item.DataItem as DataRowView;
			Label actiuneAnulata = e.Item.FindControl("actiuneAnulata") as Label;
			object cancel = data["Cancel"];
			actiuneAnulata.Visible = (0 < (int)cancel);
			LinkButton detaliiActiune = e.Item.FindControl("detaliiActiune") as LinkButton;
			detaliiActiune.CommandArgument = data["eType"].ToString()[0] + ";" + data["ID"].ToString();
			Label refId = e.Item.FindControl("refId") as Label;
			if(refId != null)
				refId.Visible = e.Item.ItemIndex > 0; // externarile (intotdeauna primele din dataset) nu au RefID
			//else
		}
	}

	protected void detaliiActiune_Click(object sender, EventArgs e)
	{
		LinkButton b = sender as LinkButton;
		string targetId = b.CommandArgument.Substring(2);
		System.Web.UI.Control c = this.Parent;
		while ((c != null) && !(c is TabContainer))
			c = c.Parent;
		TabContainer container = c as TabContainer;
		if (container == null)
			return;
		switch (b.CommandArgument[0])
		{
			case 'I':
				this.ViewState["checkinID"] = targetId;
				CheckIn p = container.Tabs[TabbedDetails.checkinTabIndex].Controls[0].FindControl("checkInPacient") as CheckIn;
				p.pacientID = this.pacientID;
				p.checkinID = targetId;
				p.LoadData();
				TabbedDetails.SetUrl(this, Request.Path + "?action=checkin&pacientID=" + pacientID + "&checkinID=" + targetId); //if (!~) SetMessage("Not found!", false);
				container.ActiveTabIndex = TabbedDetails.checkinTabIndex;
				break;
			case 'T':
				this.ViewState["transferID"] = targetId;
				break;
			case 'E':
				this.ViewState["checkoutID"] = targetId;
				//...
				container.ActiveTabIndex = TabbedDetails.checkoutTabIndex;
				break;
			default:
				//todo: show message
				return;
		}
	}

	protected void linkPresentation_Click(object sender, EventArgs e)
	{
		LinkButton b = sender as LinkButton;
		this.ViewState["presentationID"] = b.CommandArgument;
		System.Web.UI.Control c = this.Parent;
		while ((c != null) && !(c is TabContainer))
			c = c.Parent;
		
		TabContainer container = c as TabContainer;
        if (container != null)
		{
			Presentation p = container.Tabs[TabbedDetails.admissionTabIndex].Controls[0].FindControl("presentation") as Presentation;
			p.pacientID = this.pacientID;
			p.presentationID = b.CommandArgument;
			p.LoadData();
			TabbedDetails.SetUrl(this, Request.Path + "?action=admit&pacientID=" + pacientID + "&presentationID=" + b.CommandArgument);
			container.ActiveTabIndex = TabbedDetails.admissionTabIndex;
		}
	}
	
	private void SetValidators(bool enabled)
	{
		validatorFirstName.Enabled = enabled;
		validatorLastName.Enabled = enabled;
		validatorJudet.Enabled = enabled;
		validatorLocalitate.Enabled = enabled;
	}

	protected void validatorLocNastere_ServerValidate(object source, ServerValidateEventArgs args)
	{
		args.IsValid = (strBirthDistrictID.SelectedIndex == 0) || //either no County chosen
			((strBirthZoneID.Text.Length > 0) && (strBirthZoneName.Text.Length > 0)); //or the specific location was selected
	}
	
	protected string GetColourForSettlementType(string strType)
    {
        return (strType.Equals("u") ? "red" : strType.Equals("r") ? "green" : "gray");
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {

        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }

    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {

        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }

    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect("~/Default.aspx?action=search&what=PA");
        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }

    }
}
